package com.dk.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.nacos.api.utils.StringUtils;
import com.dk.enums.ResultEnum;
import com.dk.result.Result;
import com.dk.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
@Slf4j
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.excludes.url}'.empty ? null : '${gateway.excludes.url}'.split(',')}")
    private Set<String> excludes;

    private PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求头中取出token
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("请求路径:  {}", path);
        log.info("set集合的值: {}", excludes);
        //遍历set
        for (String exclude : excludes) {
            //判断请求的路径符不符合set集合中的值 如果符合就放过
            if (pathMatcher.match(exclude, path)) {
                return chain.filter(exchange);
            }
        }
        //获取
        String token = request.getHeaders().getFirst("AuthToken");
        if (StringUtils.isBlank(token)) {//说明未登录
            return response(exchange);
        }
        try {
            Claims claims = jwtUtil.parseJwt(token);
            log.info("登录用户 : {}",claims);
        }catch (Exception e){
            Claims claims = jwtUtil.parseJwt(token);
            log.info("登录用户 : {}", claims);
            return response(exchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> response(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.respones(ResultEnum.LOGIN_AUTH), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
}
